package com.lw.lost.activity.admin

import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.ManageUserAdapter
import com.lw.lost.databinding.ActivityUserManageBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.ManageUser

class UserManageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityUserManageBinding
    private lateinit var db: DBlost
    private lateinit var userAdapter: ManageUserAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityUserManageBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "用户管理"

        db = DBlost(this)
        setupRecyclerView()
        setupSearchView()
        loadUsers()
    }

    private fun setupRecyclerView() {
        userAdapter = ManageUserAdapter(
            onUserAction = { user ->
                showActionDialog(user)
            },
            onUserClick = { user ->
                showUserDetailDialog(user)
            }
        )

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = userAdapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }
    }

    private fun setupSearchView() {
        binding.searchView.apply {
            queryHint = "输入用户名或姓名搜索"
            isIconified = false // 默认展开搜索框
            
            setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(query: String?): Boolean {
                    return true
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    if (newText.isNullOrEmpty()) {
                        loadUsers()
                        binding.tvEmpty.text = "暂无用户数据"
                    } else {
                        searchUsers(newText)
                        binding.tvEmpty.text = "未找到相关用户"
                    }
                    return true
                }
            })
        }
    }

    private fun loadUsers() {
        try {
            val cursor = db.userDao.getAllUsers()
            val users = mutableListOf<ManageUser>()

            Log.d("UserManage", "Cursor count: ${cursor.count}")

            cursor.use { cursor ->
                while (cursor.moveToNext()) {
                    val status = cursor.getInt(cursor.getColumnIndexOrThrow("status"))
                    Log.d("UserManage", "User status: $status")
                    
                    if (status != 2) { // 不显示管理员账号
                        val user = ManageUser(
                            userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                            username = cursor.getString(cursor.getColumnIndexOrThrow("username")),
                            name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
                            phone = cursor.getString(cursor.getColumnIndexOrThrow("phone")),
                            gender = cursor.getInt(cursor.getColumnIndexOrThrow("gender")),
                            age = cursor.getInt(cursor.getColumnIndexOrThrow("age")),
                            status = status,
                            avatar = cursor.getString(cursor.getColumnIndexOrThrow("avatar"))
                        )
                        users.add(user)
                        Log.d("UserManage", "Added user: ${user.name}")
                    }
                }
            }

            Log.d("UserManage", "Final users count: ${users.size}")

            updateUI(users)
        } catch (e: Exception) {
            Log.e("UserManage", "Error loading users", e)
            Toast.makeText(this, "加载用户数据失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun searchUsers(keyword: String) {
        val cursor = db.userDao.searchUsers(keyword)
        val users = mutableListOf<ManageUser>()

        cursor.use { cursor ->
            while (cursor.moveToNext()) {
                val status = cursor.getInt(cursor.getColumnIndexOrThrow("status"))
                if (status != 2) {
                    users.add(
                        ManageUser(
                            userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                            username = cursor.getString(cursor.getColumnIndexOrThrow("username")),
                            name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
                            phone = cursor.getString(cursor.getColumnIndexOrThrow("phone")),
                            gender = cursor.getInt(cursor.getColumnIndexOrThrow("gender")),
                            age = cursor.getInt(cursor.getColumnIndexOrThrow("age")),
                            status = status,
                            avatar = cursor.getString(cursor.getColumnIndexOrThrow("avatar"))
                        )
                    )
                }
            }
        }

        updateUI(users, isSearchResult = true)
    }

    private fun updateUI(users: List<ManageUser>, isSearchResult: Boolean = false) {
        // 更新列表
        userAdapter.submitList(users)

        // 更新统计信息
        if (isSearchResult) {
            binding.tvUserCount.text = "找到 ${users.size} 个用户"
        } else {
            val normalUsers = users.count { it.status == 1 }
            val blockedUsers = users.count { it.status == 0 }
            binding.tvUserCount.text = "共 ${users.size} 个用户（正常: $normalUsers, 封禁: $blockedUsers）"
        }

        // 更新空状态显示
        binding.tvEmpty.visibility = if (users.isEmpty()) View.VISIBLE else View.GONE
        binding.recyclerView.visibility = if (users.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun showActionDialog(user: ManageUser) {
        val items = arrayOf("查看详情", if (user.status == 0) "解封用户" else "封禁用户", "删除用户")
        
        AlertDialog.Builder(this)
            .setTitle("用户操作")
            .setItems(items) { _, which ->
                when (which) {
                    0 -> showUserDetailDialog(user)
                    1 -> showStatusConfirmDialog(user)
                    2 -> showDeleteConfirmDialog(user)
                }
            }
            .show()
    }

    private fun showUserDetailDialog(user: ManageUser) {
        // 构建基本信息
        val basicInfo = """
            用户名：${user.username}
            姓名：${user.name}
            手机号：${user.phone}
            性别：${if (user.gender == 0) "男" else "女"}
            年龄：${user.age}
            状态：${when (user.status) {
                0 -> "已封禁"
                1 -> "正常"
                else -> "未知"
            }}
        """.trimIndent()

        // 如果用户被封禁，获取举报信息
        val reportInfo = if (user.status == 0) {
            val reportCursor = db.userDao.getUserReports(user.userId)
            val reports = StringBuilder("\n\n封禁原因：")
            
            if (reportCursor.moveToFirst()) {
                do {
                    val content = reportCursor.getString(reportCursor.getColumnIndexOrThrow("content"))
                    val time = reportCursor.getString(reportCursor.getColumnIndexOrThrow("reportTime"))
                    reports.append("\n• $content ($time)")
                } while (reportCursor.moveToNext())
            } else {
                reports.append("\n暂无举报记录")
            }
            reportCursor.close()
            reports.toString()
        } else {
            ""
        }

        // 创建带有样式的文本
        val message = SpannableStringBuilder(basicInfo + reportInfo)
        
        // 如果有举报信息，设置红色样式
        if (reportInfo.isNotEmpty()) {
            val startIndex = basicInfo.length + 1
            val endIndex = message.length
            message.setSpan(
                ForegroundColorSpan(getColor(android.R.color.holo_red_dark)),
                startIndex,
                endIndex,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        AlertDialog.Builder(this)
            .setTitle("用户详情")
            .setMessage(message)
            .setPositiveButton("确定", null)
            .show()
    }

    private fun showStatusConfirmDialog(user: ManageUser) {
        val newStatus = if (user.status == 0) 1 else 0
        val message = if (newStatus == 0) {
            "确定要封禁该用户吗？\n封禁后该用户将无法登录系统。"
        } else {
            "确定要解封该用户吗？"
        }

        AlertDialog.Builder(this)
            .setTitle("确认操作")
            .setMessage(message)
            .setPositiveButton("确定") { _, _ ->
                updateUserStatus(user.userId, newStatus)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showDeleteConfirmDialog(user: ManageUser) {
        AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定要删除该用户吗？此操作不可恢复！")
            .setPositiveButton("确定") { _, _ ->
                deleteUser(user.userId)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun updateUserStatus(userId: Long, status: Int) {
        val result = db.userDao.updateUserStatus(userId, status)
        if (result > 0) {
            Toast.makeText(this, 
                if (status == 0) "已封禁用户" else "已解封用户", 
                Toast.LENGTH_SHORT
            ).show()
            loadUsers()
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun deleteUser(userId: Long) {
        val result = db.userDao.deleteUser(userId)
        if (result > 0) {
            Toast.makeText(this, "已删除用户", Toast.LENGTH_SHORT).show()
            loadUsers()
        } else {
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
} 